package main

import (
	"github.com/panjf2000/gnet/v2"
	log "github.com/sirupsen/logrus"
	"time"
)

type Client struct {
	gnet.BuiltinEventEngine
	eng      gnet.Engine
	shutdown bool
}

func (c *Client) OnBoot(eng gnet.Engine) gnet.Action {
	c.eng = eng
	c.shutdown = false
	log.Infof("启动客户端")
	return gnet.None
}

func (c *Client) OnTraffic(conn gnet.Conn) gnet.Action {
	buf, _ := conn.Next(-1)
	log.Infoln("Received Message:", string(buf))
	c.shutdown = true
	return gnet.None
}

//// OnTick 注意到返回值为time.Second，代表下一次执行这个函数为一秒钟以后，如果
//func (c *Client) OnTick() (delay time.Duration, action gnet.Action) {
//	delay = time.Second
//	action = gnet.None
//	if c.shutdown {
//		delay = 0
//		action = gnet.Shutdown
//		log.Infoln("检测到数据接收已经结束，关闭客户端。。。")
//		return 0, gnet.Shutdown
//	}
//	log.Infoln("[OnTick]-被执行")
//	return
//}

func main() {
	client := &Client{}
	cli, _ := gnet.NewClient(client, gnet.WithMulticore(true))
	dial, err := cli.Dial("tcp", "localhost:7878")
	err = cli.Start()
	if err != nil {
		log.Infoln("连接出错：" + err.Error())
		return
	}
	// 触发客户端的第一次发送
	_, _ = dial.Write([]byte("hello"))

	time.Sleep(time.Second * 4)

}
